package br.com.management.mentor.app.listeners.persisters;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

import br.com.management.mentor.app.Config;
import br.com.management.mentor.model.entities.auth.Permission;
import br.com.management.mentor.model.entities.auth.User;
import br.com.management.mentor.model.repositories.PermissionsRepository;
import br.com.management.mentor.model.repositories.UsersRepository;

import com.google.gson.reflect.TypeToken;

public class AdminsEntityPersister implements EntityPersister<User> {

	@Autowired
	private UsersRepository usersRepository;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private PermissionsRepository permissionsRepository;

	@Override
	public void persist( EntityManager em , Collection<User> entities ) {
		if ( usersRepository.thereIsAdmin() )
			return;

		for ( User user : entities ) {
			if ( usersRepository.getByUsername( user.getUsername() ) == null ) {
				user.setCreationDate( new Date() );
				user.setUpdatedDate( new Date() );

				Set<Permission> permissions = user.getAuthorities();
				Set<Permission> loadedPermissions = new HashSet<>( permissions.size() );

				for ( Permission p : permissions )
					loadedPermissions.add( permissionsRepository.getByName( p.getName() ) );
				user.setPermissions( loadedPermissions );

				user.setPassword( passwordEncoder.encode( user.getPassword() ) );
				em.persist( user );
			}
		}

	}

	@Override
	public Config getResourcePath() {
		return Config.ADMINS_SOURCE_FILE;
	}

	@Override
	public Type getEntityType() {
		return new TypeToken<Collection<User>>() {}.getType();
	}

}